/*

 * Copyright (C) 2021 Huawei Device Co., Ltd.

 * Licensed under the Apache License, Version 2.0 (the "License");

 * you may not use this file except in compliance with the License.

 * You may obtain a copy of the License at

 *

 *     http://www.apache.org/licenses/LICENSE-2.0

 *

 * Unless required by applicable law or agreed to in writing, software

 * distributed under the License is distributed on an "AS IS" BASIS,

 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

 * See the License for the specific language governing permissions and

 * limitations under the License.

 */

package me.panpf.sketch.sample.vt.ui.listcontainer;

import ohos.agp.components.AttrSet;
import ohos.agp.components.Component;
import ohos.agp.components.ComponentContainer;
import ohos.app.Context;

/**
 * SimpleViewSwitcher
 *
 * @author hw
 * @since 2021/6/23
 */
public class SimpleViewSwitcher extends ComponentContainer {
    public SimpleViewSwitcher(Context context) {
        super(context);
        init();
    }

    public SimpleViewSwitcher(Context context, AttrSet attrSet) {
        super(context, attrSet);
        init();
    }

    public SimpleViewSwitcher(Context context, AttrSet attrSet, String styleName) {
        super(context, attrSet, styleName);
        init();
    }

    private void init() {
        setEstimateSizeListener(new EstimateSizeListener() {
            @Override
            public boolean onEstimateSize(int widthEstimateConfig, int heightEstimateConfig) {
                int childCount = SimpleViewSwitcher.this.getChildCount();
                int maxHeight = 0;
                int maxWidth = 0;
                for (int i = 0; i < childCount; i++) {
                    Component child = SimpleViewSwitcher.this.getComponentAt(i);
                    maxWidth = child.getEstimatedWidth();
                    maxHeight = child.getEstimatedHeight();
                }
                setEstimatedSize(maxWidth, maxHeight);
                return true;
            }
        });
        setLayoutRefreshedListener(new LayoutRefreshedListener() {
            @Override
            public void onRefreshed(Component component) {
                final int count = getChildCount();
                for (int i = 0; i < count; i++) {
                    final Component child = getComponentAt(i);
                    if (child.getVisibility() != HIDE) {
                        child.arrange(0, 0, getWidth() - getLeft(), getHeight() - getTop());
                    }
                }
            }
        });
    }

    /**
     * setView
     *
     * @param componet componet
     */
    public void setView(Component componet) {
        if (this.getChildCount() != 0) {
            this.removeComponentAt(0);
        }
        this.addComponent(componet, 0);
    }
}